<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>差旅报销管理系统</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css">
    <style>
        .main-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
        }

        /* 表格样式 */
        #ID-table-demo-page {
            background: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,.1);
        }

        /* 表单弹窗样式 */
        .form-dialog {
            padding: 20px 30px;
        }

        /* 动态项样式 */
        .dynamic-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .dynamic-item .layui-input {
            flex: 1;
            margin-right: 10px;
        }
        .dynamic-item .layui-btn {
            flex-shrink: 0;
        }

        /* 金额输入框样式 */
        .amount-input {
            position: relative;
        }
        .amount-input:after {
            content: "¥";
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
        }
        /* 新增样式 */
        .dynamic-item {
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 4px;
            margin-bottom: 15px;
            background: #f8f8f8;
        }
        .trip-item {
            padding: 15px;
            margin-bottom: 15px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            background: #fafafa;
        }

        .mini-label {
            width: 80px !important;
            padding: 9px 5px !important;
        }

        .date-input {
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18"><path fill="%23999" d="M19 4h-1V2h-2v2H8V2H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V10h14v10zM5 8V6h14v2H5z"/></svg>');
            background-repeat: no-repeat;
            background-position: 98% center;
            background-size: 18px;
        }

        .amount-input:after {
            content: "¥";
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
            font-size: 14px;
        }

        .text-right {
            text-align: right;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div class="main-container">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-lg" id="insert">
            <i class="layui-icon layui-icon-add-1"></i> 新建报销单
        </button>
    </div>

    <table class="layui-hide" id="ID-table-demo-page"></table>
</div>

<!-- 工具栏模板 -->
<script type="text/html" id="rowToolbar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="download">下载</a>
</script>

<!-- 新增表单模板 -->
<div id="addForm" style="display: none;">
    <div class="form-dialog">
        <form class="layui-form" lay-filter="form-demo">
            <div class="layui-row layui-col-space15">
                <!-- 左列 -->
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">单据名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" required lay-verify="required"
                                   autocomplete="off" class="layui-input" placeholder="自动生成">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">出差事由</label>
                        <div class="layui-input-block">
                            <textarea name="reason" required lay-verify="required"
                                      class="layui-textarea" placeholder="请输入详细出差事由"></textarea>
                        </div>
                    </div>
                </div>

                <!-- 右列 -->
                <div class="layui-col-md6">
<!--                    机、车、船票系统自己计算-->
<!--                    <div class="layui-form-item">-->
<!--                        <label class="layui-form-label">机、车、船票</label>-->
<!--                        <div class="layui-input-block amount-input">-->
<!--                            <input type="number" name="ticket" required lay-verify="required|number"-->
<!--                                   step="0.01" class="layui-input" placeholder="0.00">-->
<!--                        </div>-->
<!--                    </div>-->

                    <div class="layui-form-item">
                        <label class="layui-form-label">住宿费用</label>
                        <div class="layui-input-block amount-input">
                            <input type="number" name="quarterage" required lay-verify="number"
                                   step="0.01" class="layui-input" placeholder="0.00">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">餐饮补贴</label>
                        <div class="layui-input-block amount-input">
                            <input type="number" name="foodallowance" required lay-verify="number"
                                   step="1" class="layui-input" placeholder="0.00">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">市内交通费用</label>
                        <div class="layui-input-block amount-input">
                            <input type="number" name="cityticket" required lay-verify="number"
                                   step="1" class="layui-input" placeholder="0.00">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 其他动态添加区域 -->
            <div class="layui-form-item">
                <label class="layui-form-label">其他费用</label>
                <div class="layui-input-block">
                    <div id="dynamic-items">
                        <div class="dynamic-item">
                            <input type="text" name="other_name[]" placeholder="费用名称" class="layui-input">
                            <input type="number" name="other_price[]" step="0.01" placeholder="金额" class="layui-input">
                            <button type="button" class="layui-btn layui-btn-danger layui-btn-xs btn-remove">
                                <i class="layui-icon layui-icon-close"></i>
                            </button>
                        </div>
                    </div>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="add-item">
                        <i class="layui-icon layui-icon-add-1"></i> 添加费用项
                    </button>
                </div>
            </div>

            <!-- 详情动态添加区域 -->
           <!-- 修改后的动态添加区域 -->
            <!-- 优化后的行程明细动态添加区域 -->
            <div class="layui-form-item">
                <label class="layui-form-label">行程明细</label>
                <div class="layui-input-block">
                    <div id="ordel">
                        <!-- 单个行程条目模板 -->
                        <div class="trip-item">
                            <div class="layui-row layui-col-space15">
                                <!-- 日期行 -->
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">出发日期</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="start_date[]"
                                                   class="layui-input date-input"
                                                   placeholder="选择日期">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">结束日期</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="end_date[]"
                                                   class="layui-input date-input"
                                                   placeholder="选择日期">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 地点行 -->
                            <div class="layui-row layui-col-space15">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">出发地</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="Start_location[]"
                                                   class="layui-input"
                                                   placeholder="请输入出发地">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">目的地</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="End_location[]"
                                                   class="layui-input"
                                                   placeholder="请输入目的地">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 天数与金额 -->
                            <div class="layui-row layui-col-space15">
                                <div class="layui-col-md3">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">在途天数</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="Days_in_transit[]"
                                                   class="layui-input"
                                                   placeholder="天数" min="0">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md3">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">住勤天数</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="Stayperiod[]"
                                                   class="layui-input"
                                                   placeholder="天数" min="0">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md3">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">备注说明</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="Comment[]"
                                                   class="layui-input"
                                                   placeholder="请输入备注">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md3">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label mini-label">金额</label>
                                        <div class="layui-input-block amount-input">
                                            <input type="number" name="Money[]"
                                                   class="layui-input"
                                                   placeholder="0.00" step="0.01" min="0">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 操作按钮 -->
                            <div class="layui-form-item text-right">
                                <button type="button"
                                        class="layui-btn layui-btn-sm layui-btn-danger btn-remove_order">
                                    <i class="layui-icon layui-icon-delete"></i> 删除本条
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 添加按钮 -->
                    <div class="layui-form-item">
                        <button type="button"
                                class="layui-btn layui-btn-sm layui-btn-primary"
                                id="add-ordel">
                            <i class="layui-icon layui-icon-add-1"></i> 添加行程
                        </button>
                    </div>
                </div>
            </div>

         <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formSubmit">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>

        </form>
    </div>
</div>

<!-- 依赖库 -->
<script src="/static/jquery-3.7.1/jquery-3.7.1.min.js"></script>
<script src="/static/layui/layui.js"></script>

<script>
layui.use(['table', 'layer', 'form', 'laydate'], function() {
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var laydate = layui.laydate;

    // 初始化日期选择器
    laydate.render({
        elem: '#start-date',
        trigger: 'click',
        format: 'yyyy-MM-dd'
    });

    // 表格初始化
    table.render({
        elem: '#ID-table-demo-page',
        url: '/rmb/api/getTravelReimburse',
        page: true,
        cols: [[
            {field: 'id', title: 'ID', width: 100, sort: true},
            {field: 'name', title: '单据名称', minWidth: 180},
            {field: 'total_amount', title: '总金额', width: 120},
            {field: 'create_time', title: '创建时间', width: 180},
            {fixed: 'right', title: '操作', width: 200, toolbar: '#rowToolbar'}
        ]]
    });
        // 监听工具事件（用于行内按钮）
    table.on('tool(ID-table-demo-page)', function(obj) { // 注意：这里的值需要与table的elem对应
        var data = obj.data; // 获取当前行数据
        if (obj.event === 'download') { // 下载按钮事件
            window.location.href = '/rmb/api/getrbmexecl?ctid=' + data.id; // 根据ID生成下载链接
        }
        else if (obj.event === 'edit') {
        handleEdit(data);
        }
        else if (obj.event === 'delete') {
            handleDelete(data.id);
        }
    });
    // 新增删除处理函数
    function handleDelete(id) {
        layer.confirm('确认删除该记录吗？', {
            title: '删除确认',
            icon: 3,
            btn: ['确认', '取消']
        }, function(index) {
            layer.close(index);
            $.ajax({
                url: '/rmb/api/deleteTravelReimburse',
                data :{
                    id:id,
                },
                type: 'post',
                success: function(res) {
                    if (res.code === 0) {
                        layer.msg('删除成功');
                        table.reload('ID-table-demo-page');
                    } else {
                        layer.msg(res.msg || '删除失败');
                    }
                },
                error: function() {
                    layer.msg('请求失败，请检查网络');
                }
            });
        });
    }
        $('#get').click(function() {
            window.location.href = '/rmb/api/getrbmexecl?filename=1';
        });
    // 动态添加费用项
    $('#add-item').click(function() {
        const newItem = $(`<div class="dynamic-item">
            <input type="text" name="other_name[]" placeholder="费用名称" class="layui-input">
            <input type="number" name="other_price[]" step="0.01" placeholder="金额" class="layui-input">
            <button type="button" class="layui-btn layui-btn-danger layui-btn-xs btn-remove">
                <i class="layui-icon layui-icon-close"></i>
            </button>
        </div>`);

        $('#dynamic-items').append(newItem);
        form.render();
    });

    // 删除费用项
    $(document).on('click', '.btn-remove', function() {
        if ($('#dynamic-items').children().length > 1) {
            $(this).parent().remove();
        } else {
            layer.msg('至少保留一项费用');
        }
    });

    // 动态添加行程
    $('#add-ordel').click(function() {
        const newItem = $('.trip-item').first().clone();

        // 清空输入值
        newItem.find('input').val('');

        // 重新初始化日期选择器
        newItem.find('.date-input').each(function() {
            layui.laydate.render({
                elem: this,
                trigger: 'click',
                type: 'datetime', // 增加类型
                format: 'yyyy-MM-dd  HH:mm:ss'
            });
        });

        $('#ordel').append(newItem);
    });

    // 初始化日期选择器
    layui.laydate.render({
        elem: '.date-input',
        trigger: 'click',
        type: 'datetime', // 增加类型
        format: 'yyyy-MM-dd  HH:mm:ss'
    });

    // 删除行程
    $(document).on('click', '.btn-remove_order', function() {
        if($('#ordel .trip-item').length > 1) {
            $(this).closest('.trip-item').remove();
        } else {
            layer.msg('至少保留一条行程');
        }
    });


    // 新增按钮事件
    $('#insert').click(function() {
        layer.open({
            type: 1,
            title: '新建报销单',
            content: $('#addForm'),
            area: ['800px', '90%'],
            success: function() {
                // 自动生成单据名称
                const now = new Date();
                const defaultName = `报销单_${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2,'0')}${now.getDate().toString().padStart(2,'0')}`;
                $('input[name="name"]').val(defaultName);
            }
        });
    });

    // 表单提交
form.on('submit(formSubmit)', function(data){
    // 获取基础表单数据
    const formData = data.field;

    // 处理其他费用项
    const otherItems = [];
    $('[name="other_name[]"]').each(function(index) {
        const name = $(this).val();
        const price = $('[name="other_price[]"]').eq(index).val();
        if (name && price) {
            otherItems.push({
                item_name: name,
                amount: parseFloat(price)
            });
        }
    });

    // 处理行程明细
    const tripDetails = [];
    $('.trip-item').each(function(index) {
        const tripItem = {
            start_date: $(this).find('[name="start_date[]"]').val(),
            end_date: $(this).find('[name="end_date[]"]').val(),
            departure: $(this).find('[name="Start_location[]"]').val(),
            destination: $(this).find('[name="End_location[]"]').val(),
            transit_days: parseInt($(this).find('[name="Days_in_transit[]"]').val()) || 0,
            stay_days: parseInt($(this).find('[name="Stayperiod[]"]').val()) || 0,
            remark: $(this).find('[name="Comment[]"]').val(),
            amount: parseFloat($(this).find('[name="Money[]"]').val()) || 0
        };

        if (tripItem.start_date && tripItem.end_date) {
            tripDetails.push(tripItem);
        }
    });

    // 构建完整数据对象
        const postData = {
            basic_info: {
                document_name: formData.name,
                reason: formData.reason
            },
            cost_details: {
                accommodation: parseFloat(formData.quarterage) || 0,
                meal_subsidy: parseFloat(formData.foodallowance) || 0,
                local_transport: parseFloat(formData.cityticket) || 0
            },
            additional_costs: otherItems,
            trip_schedules: tripDetails
        };

        // 提交到后端
        $.ajax({
            url: '/rmb/api/addTravelReimburse',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(postData),
            success: function(res) {
                if (res.code === 0) {
                    layer.msg('提交成功');
                    table.reload('ID-table-demo-page');
                    layer.closeAll();
                } else {
                    layer.msg(res.msg || '提交失败');
                }
            },
            error: function(xhr) {
                layer.msg(`请求失败: ${xhr.statusText}`);
            }
        });
        return false;
    });
});
</script>
</body>
</html>